import React from 'react';
import {Spin, Card, Button, Row, Col, Form} from 'antd';
import PropTypes from 'prop-types';
import routes from './routes';
import {FORM_OPTIONS, FORM_ROW_OPTIONS} from '../constants';
import {addApplyReport} from './api';
import TextInput from 'Shared/components/TextInput';
import SearchInput from 'Shared/components/SearchInput';
import InputPercent from '../common/InputPercent';
import PartSelectPanel from './PartSelectPanel';
import WrappedDatePicker from '../common/WrappedDatePicker';
import DutyUnitSelectPanel from './DutyUnitSelectPanel';
import ReplacedDutyUnitSelectPanel from './ReplacedDutyUnitSelectPanel';
import {injectIntl} from './intl';
import WrappedSelect from '../common/WrappedSelect';
import LocalizeInputNumber from '../common/LocalizeInputNumber';
import styles from './style.css';
import Return from '../common/Return';
import {newOrUpdateOrderValidator} from './validator';
const FormItem = Form.Item;

class AddPanel extends React.PureComponent {
    state = {
        loading: false,
        hasOperat: false,
        isValidate: false,
        showPartSelectPanel: false,
        showDutyUnitSelectPanel: false,
        showReplacedDutyUnitSelectPanel: false,
        data: {},
    }
    componentWillUnmount() {
        this.isunmount = true;
    }
    onChange = (value, name) => {
        const data = Object.assign({}, this.state.data, {
            [name]: value
        });
        this.setState({
            data,
            hasOperat: true
        });
    }
    onClickOkOnPopconfirm = () => {
        this.props.onCancel();
    }
    onSubmit = () => {
        const data = this.state.data;
        const isValid = newOrUpdateOrderValidator(data);
        if(!isValid) {
            this.setState({
                isValidate: true
            });
            return;
        }
        const condition = {
            code: data.code,
            brandId: data.brandId,
            dutyUnitId: data.dutyUnitId,
            replacedDutyUnitId: data.replacedDutyUnitId,
            partId: data.partId,
            shareRate: data.shareRate,
            endDate: data.endDate,
            remark: data.remark,
            startTime: data.startTime,
            endTime: data.endTime,
            faultReason: data.faultReason,
        };
        this.setState({loading: true});
        addApplyReport(condition).then(res => {
            if(res.ok)
                this.props.successReturn();
            if(!this.isunmount)
                this.setState({loading: false});
        });
    }
    onClickSearchPartBtn = () => {
        this.setState({
            showPartSelectPanel: true
        });
    }
    onClosePartSelectPanel = () => {
        this.setState({showPartSelectPanel: false}); 
    }
    onSelectPart = records => {
        this.setState({
            data: Object.assign({}, this.state.data, {
                partId: records.id,
                partCode: records.code,
            }),
            hasOperat: true,
            showPartSelectPanel: false
        });
    }
    onClickSearchDutyUnitBtn = () => {
        this.setState({
            showDutyUnitSelectPanel: true
        });
    }
    onCloseDutyUnitSelectPanel = () => {
        this.setState({showDutyUnitSelectPanel: false});
    }
    onSelectDutyUnit = records => {
        this.setState({
            data: Object.assign({}, this.state.data, {
                dutyUnitId: records.id,
                dutyUnitCode: records.code,
                dutyUnitName: records.name,
            }),
            hasOperat: true,
            showDutyUnitSelectPanel: false
        });
    }
    onClickSearchReplacedDutyUnitBtn = () => {
        this.setState({
            showReplacedDutyUnitSelectPanel: true
        });
    }
    onCloseReplacedDutyUnitSelectPanel = () => {
        this.setState({showReplacedDutyUnitSelectPanel: false});
    }
    onSelectReplacedDutyUnit = records => {
        this.setState({
            data: Object.assign({}, this.state.data, {
                replacedDutyUnitId: records.id,
                replacedDutyUnitCode: records.code,
                replacedDutyUnitName: records.name,
            }),
            hasOperat: true,
            showReplacedDutyUnitSelectPanel: false
        });
    }
    render() {
        const {formatMessage} = this.props.intl;
        const {data, isValidate, loading} = this.state;
        const {brands} = this.props.initEnumData;
        if(brands.length === 1 && !this.props.id) {
            data.brandId = brands[0].value;
            data.brandName = brands[0].text;
        }
        return (
            <div className="form-standard">
                <Spin spinning={this.state.loading}>
                    <Card title={formatMessage({
                        id: 'addPanel.column.common',
                        defaultMessage: '质量仲裁信息'
                    })}>
                        <Form>
                            <Row>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'addPanel.operation.code',
                                        defaultMessage: '仲裁编号'
                                    })}{...FORM_OPTIONS.item} validateStatus={isValidate && !data.code ? 'error' : null} required>
                                        <TextInput
                                            name="code"
                                            value={data.code}
                                            onBlur={this.onChange} />
                                    </FormItem>
                                </Col>
                                {brands.length !== 1 && <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'addPanel.operation.brandName',
                                        defaultMessage: '品牌'
                                    })}{...FORM_OPTIONS.item} validateStatus={isValidate && !data.brandId ? 'error' : null} required>
                                        <WrappedSelect
                                            name="brandId"
                                            value={data.brandId}
                                            options={brands}
                                            onChange={this.onChange}/>
                                    </FormItem>
                                </Col>}
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'addPanel.operation.dutyUnitId',
                                        defaultMessage: '原供应商'
                                    })} {...FORM_OPTIONS.item} validateStatus={isValidate && !data.dutyUnitId ? 'error' : null} required>
                                        <SearchInput
                                            disabled={true}
                                            value={data.dutyUnitCode === undefined ? '' : `(${data.dutyUnitCode})${data.dutyUnitName}`}
                                            onClickSearchBtn={() => this.onClickSearchDutyUnitBtn()} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'addPanel.operation.replacedDutyUnitId',
                                        defaultMessage: '替换供应商'
                                    })} {...FORM_OPTIONS.item} validateStatus={isValidate && !data.replacedDutyUnitId ? 'error' : null} required>
                                        <SearchInput
                                            disabled={true}
                                            value={data.replacedDutyUnitCode === undefined ? '' : `(${data.replacedDutyUnitCode})${data.replacedDutyUnitName}`}
                                            onClickSearchBtn={() => this.onClickSearchReplacedDutyUnitBtn()} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'addPanel.data.partId',
                                        defaultMessage: '判定零件编号'
                                    })}{...FORM_OPTIONS.item}>
                                        <SearchInput
                                            disabled={true}
                                            value={data.partCode}
                                            onClickSearchBtn={() => this.onClickSearchPartBtn()} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'addPanel.operation.shareRate',
                                        defaultMessage: '承担比例'
                                    })} {...FORM_OPTIONS.item} validateStatus={isValidate && !data.shareRate ? 'error' : null} required>
                                        <InputPercent
                                            name="shareRate"
                                            value={data.shareRate}
                                            onBlur={this.onChange}/>
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'addPanel.operation.endDate',
                                        defaultMessage: '有效截止日期'
                                    })} {...FORM_OPTIONS.item} validateStatus={isValidate && !data.endDate ? 'error' : null} required>
                                        <WrappedDatePicker
                                            name="endDate"
                                            value={data.endDate}
                                            onChange={this.onChange}/>
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'addPanel.operation.startTime',
                                        defaultMessage: '生产开始时间'
                                    })} {...FORM_OPTIONS.item}>
                                        <WrappedDatePicker
                                            name="startTime"
                                            value={data.startTime}
                                            onChange={this.onChange}/>
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'addPanel.operation.endTime',
                                        defaultMessage: '生产结束时间'
                                    })} {...FORM_OPTIONS.item}>
                                        <WrappedDatePicker
                                            name="endTime"
                                            value={data.endTime}
                                            onChange={this.onChange}/>
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row>
                                <Col>
                                    <FormItem label={formatMessage({
                                        id: 'addPanel.text.faultReason',
                                        defaultMessage: '故障原因'
                                    })} {...FORM_ROW_OPTIONS.item}>
                                        <TextInput
                                            type="textarea"
                                            name="faultReason"
                                            value={data.faultReason}
                                            onBlur={this.onChange} />
                                    </FormItem>
                                </Col>
                                <Col>
                                    <FormItem label={formatMessage({
                                        id: 'addPanel.text.remark',
                                        defaultMessage: '备注'
                                    })} {...FORM_ROW_OPTIONS.item}>
                                        <TextInput
                                            type="textarea"
                                            name="remark"
                                            value={data.remark}
                                            onBlur={this.onChange} />
                                    </FormItem>
                                </Col>
                            </Row>
                        </Form>
                    </Card>
                    <Card className={styles.optionBtn}>
                        <Button
                            type="primary"
                            onClick={this.onSubmit}
                            loading={loading}>
                            {formatMessage({
                                id: 'addPanel.operation.onSubmit',
                                defaultMessage: '保存'
                            })}
                        </Button>
                    </Card>
                </Spin>
                {
                    this.state.showPartSelectPanel &&
                    <PartSelectPanel
                        selectKey={data.productId}
                        onCancel={this.onClosePartSelectPanel}
                        onSelect={this.onSelectPart} />
                }
                {
                    this.state.showDutyUnitSelectPanel &&
                    <DutyUnitSelectPanel
                        selectKey={data.dutyUnitId}
                        onCancel={this.onCloseDutyUnitSelectPanel}
                        onSelect={this.onSelectDutyUnit} />
                }
                {
                    this.state.showReplacedDutyUnitSelectPanel &&
                    <ReplacedDutyUnitSelectPanel
                        selectKey={data.replacedDutyUnitId}
                        onCancel={this.onCloseReplacedDutyUnitSelectPanel}
                        onSelect={this.onSelectReplacedDutyUnit} />
                }
                <div className="page-toolbar">
                    <Return
                        disabled={this.state.loading}
                        onConfirm={this.onClickOkOnPopconfirm}
                        showWarning={this.state.hasOperat} />
                </div>
            </div>
        );
    }
}

AddPanel.propTypes = {
    successReturn: PropTypes.func.isRequired,
    onCancel: PropTypes.func.isRequired,
    onSelect: PropTypes.func.isRequired,
    history: PropTypes.object,
    id: PropTypes.string,
    intl: PropTypes.object,
};

import {connect} from 'react-redux';
import {
    tableSearch,
    saveQueryDealer
} from './actions';
import {createSelector} from 'reselect';

const getinitEnumData = createSelector(
    state => state.getIn(['page', 'domainData', 'init']),
    init => {
        const initData = init.toJS();
        const brands = initData.brands ? initData.brands.map(item => ({
            text: `(${item.code})${item.name}`,
            value: item.id
        })) : [];
        return {
            brands,
        };
    }
);
const mapStateToProps = state => ({
    initEnumData: getinitEnumData(state),
});
const mapDispatchToProps = (dispatch, props) => ({
    onSelect: data => dispatch(saveQueryDealer(data)),
    successReturn: () => {
        dispatch(tableSearch());
        props.history.push(routes.query.url());
    },
    onCancel: () => {
        props.history.push(routes.query.url());
    },
});
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(AddPanel));
